<template>
  <div class="p-15 bg-f2">
    <el-form class="pAll bg-fff" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="服务端地址:" prop="iotIp">
            <el-input v-model.trim="ruleForm.iotIp" clearable placeholder="服务端地址"></el-input>
          </el-form-item>
          <el-form-item label="端口号:" prop="iotdk">
            <el-input v-model.trim="ruleForm.iotdk" clearable placeholder="65535"></el-input>
          </el-form-item>
          <!-- <el-form-item label="MQTT账号:" prop="iotzh">
            <el-input v-model.trim="ruleForm.iotzh" clearable placeholder="MQTT账号"></el-input>
          </el-form-item>
          <el-form-item label="MQTT密码:" prop="iotmm">
            <el-input v-model.trim="ruleForm.iotmm" clearable placeholder="MQTT密码"></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button :loading="buttonLoad" type="primary" class="btnSizeStyle" size="medium" @click="baoCun('ruleForm')" v-preventReClick>保存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <div class="fooer_btn">
        <el-button type="primary" size="medium" @click="baoCun('ruleForm')" v-preventReClick>保存</el-button>
      </div>-->
    </el-form>
  </div>
</template>
<script>
import { pinT, iotUrl } from '@/utils/allUrl.js'
// import mqtt from 'mqtt'
export default {
  data() {
    return {
      ruleForm: {
        iotIp: '',
        iotdk: '',
        iotzh: '',
        iotmm: '',
      },
      peiziID: '', // 配置id
      rules: {
        iotIp: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          {
            pattern: /[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/,
            message: '请输入正确的服务器地址地址',
            trigger: 'blur',
          },
        ],
        iotzh: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符之间', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/, message: '请输入数字或者字母', trigger: 'blur' },
        ],
        iotmm: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符之间', trigger: 'blur' },
          {
            pattern: /(?!bai([a-zA-Z\d]+|du[a-zA-Z`~zhidao\!@#\$%\^&\*\(\)\-_=\+\[\{\]\}\\\|;:\'\",<\.>\/\?]+|[\d`~\!@#\$%\^&\*\(\)\-_=\+\[\{\]\}\\\|;:\'\",<\.>\/\?]+)$)[a-zA-Z\d`~\!@#\$%\^&\*\(\)\-_=\+\[\{\]\}\\\|;:\'\",<\.>\/\?]+$/,
            message: '请输入字母、数字、符号',
            trigger: 'blur',
          },
        ],
        iotdk: [
          { required: true, message: '此次为必填项', trigger: 'blur' },
          { pattern: /^-?[0-9]\d*$/, message: '只能输入数字', trigger: 'selecet' },
          { min: 0, max: 5, message: '长度在 5 个字符之间', trigger: 'blur' },
        ],
      },
      options: {
        clean: true, // true: 清除会话, false: 保留会话
        connectTimeout: 4000, // 超时时间
        endpoint: '/mqtt',
        // 认证信息
        clientId: 'cmmop-client-test',
        username: 'admin0002',
        password: 'admin0002',
        // securemode: 3,
      },
      client: null,
      buttonLoad: false,
    }
  },
  created() {
    //   获取数据
    this.getList()
  },
  methods: {
    async getList() {
      const { data: res } = await this.$http.post(`${pinT}iot/selectLot`)
      if (res.code === '0000') {
        if (res.data.lon) {
          const { ip, port, mqtt_ACCOUNT, mqtt_PASSWORD, id } = res.data.lon
          this.ruleForm = {
            iotIp: ip,
            iotdk: port,
            iotzh: mqtt_ACCOUNT,
            iotmm: mqtt_PASSWORD,
          }
          this.peiziID = id
        }
      } else {
        this.ruleForm = {
          iotIp: '',
          iotdk: '',
          iotzh: '',
          iotmm: '',
        }
        this.peiziID = ''
        this.$message({
          type: 'error',
          message: res.message,
          center: true,
        })
      }
    },
    baoCun(ruleForm) {
      this.buttonLoad = true
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.createConnection()
        } else {
          this.goliebiao = false
          this.buttonLoad = false
          return this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true,
          })
        }
      })
    },
    async successBtn() {
      const { iotIp, iotdk } = this.ruleForm
      // const { iotIp, iotdk, iotzh, iotmm } = this.ruleForm
      const params = new URLSearchParams()
      if (this.peiziID) {
        params.append('ID', this.peiziID)
      }
      params.append('IP', iotIp)
      params.append('PORT', iotdk)
      // params.append('MQTT_ACCOUNT', iotzh)
      // params.append('MQTT_PASSWORD', iotmm)
      const { data: res } = await this.$http.post(`${pinT}iot/inserOrUpdatetLot`, params)
      this.buttonLoad = false
      switch (res.code) {
        case '0000':
          this.$message({
            type: 'success',
            message: res.message,
            center: true,
          })
          break
        default:
          this.$message({
            type: 'error',
            message: res.message,
            center: true,
          })
          break
      }
    },
    // 创建连接
    async createConnection() {
      var codeRem = {
        R_0000: '成功',
        R_0001: '失败',
        R_0003: '错误',
      }
      // const connectUrl = `ws://${this.ruleForm.iotIp}:${this.ruleForm.iotdk}/mqtt`
      const { data: res } = await this.$http.get(`${iotUrl}client/mqtt/clientMqtt?tcpUrl=${this.ruleForm.iotIp}&port=${this.ruleForm.iotdk}`)
      // console.log(res)
      switch (res) {
        case '0000':
          this.successBtn()
          break
        default:
          this.buttonLoad = false
          this.$message.error(codeRem[`R_${res}`])
          break
      }
      // this.client = mqtt.connect(connectUrl, this.options)
      // // 建立连接
      // this.client.on('connect', function (data) {
      //   console.log(data)
      //   if (!data) {
      //     this.successBtn()
      //   } else {
      //     this.buttonLoad = false
      //     this.$message.error('请检查服务端地址和端口号是否正确')
      //   }
      // })
      // this.client.on('reconnect', (error) => {
      //   if (error === undefined) {
      //     this.client.reconnecting = false
      //     this.buttonLoad = false
      //     this.client.end()
      //     this.$message.error('请检查服务端地址和端口号是否正确')
      //   }
      // })
    },
  },
  destroyed() {
    console.log(this.client)
    if (this.client) {
      // this.client.disconnect()
      this.client.end()
    }
  },
}
</script>
<style lang="scss" scoped>
.fooer_btn {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>
